package cn.com.longfuinfo.wx.controller;



import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jfinal.aop.Duang;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.OrderRefundApi;
import com.jfinal.weixin.sdk.api.OrderSuccessApi;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.api.PaymentApi.TradeType;
import com.jfinal.weixin.sdk.kit.PaymentKit;

import cn.com.longfuinfo.wx.common.OrderCode;
import cn.com.longfuinfo.wx.common.SysConfig;
import cn.com.longfuinfo.wx.dao.GoodSpec;
import cn.com.longfuinfo.wx.dao.Goods;
import cn.com.longfuinfo.wx.dao.Order;
import cn.com.longfuinfo.wx.dao.OrderPayAPIRecord;
import cn.com.longfuinfo.wx.dao.OrderRefund;
import cn.com.longfuinfo.wx.dao.OrderRefundAPIRecord;
import cn.com.longfuinfo.wx.dao.User;
import cn.com.longfuinfo.wx.dao.UserMess;
import cn.com.longfuinfo.wx.dao.UserMoney;
import cn.com.longfuinfo.wx.dao.UserValueLog;
import cn.com.longfuinfo.wx.dao.WxUser;
import cn.com.longfuinfo.wx.exception.SaveException;
import cn.com.longfuinfo.wx.kit.CommonKit;
import cn.com.longfuinfo.wx.kit.DatetimeKit;
import cn.com.longfuinfo.wx.kit.DoubleKit;
import cn.com.longfuinfo.wx.kit.MapKit;
import cn.com.longfuinfo.wx.kit.SMSKit;
import cn.com.longfuinfo.wx.service.GoodsService;
import cn.com.longfuinfo.wx.service.OrderService;
import cn.com.longfuinfo.wx.service.UserService;

//@Before(AuthLoginInterceptor.class)
public class OrderController extends BaseController {
	private Logger logger = Logger.getLogger(getClass());
	// 使用Duang.duang进行封装，使普通类具有事务的功能
	private OrderService service = Duang.duang(OrderService.class);
	private GoodsService goodservice = Duang.duang(GoodsService.class);
	private UserService userservice = Duang.duang(UserService.class);

	/**
	 * 保存订单<br/>
	 * 在保存订单时，需要验证<br/>
	 * 1.验证所购买商品是否是“上架”状态 2.对商品数量是否超过限购数量作验证，如果不符合则保存不在成功
	 * 
	 * @param payType
	 *            支付方式
	 * @param takeType
	 *            取货方式
	 * @param linkName
	 *            联系人姓名
	 * @param sex
	 *            性别
	 * @param tel
	 *            电话
	 * @param address
	 *            地址
	 * @param describe
	 *            订单备注
	 * @return forwardFlag 1:跳转到支付页面，2：跳转到订单列表
	 */
	public void save() {

		String goodsid = getPara("goodsid");//商品id
		String tel = getPara("tel");//电话
		int pointType = getParaToInt("pointType", 0);//积分类型
		String storeid = getPara("storeid");//店铺id
		String describe = getPara("describe");//订单备注
		String amount = getPara("amount");//订单金额
		int type = getParaToInt("type", 0);//支付方式：1：货币；2：积分;3:货币积分4：多选
		String point = "0";
		if (type != 1) {
			point = getPara("point");
		}
		String goodsName = getPara("goodsName");
		String goodsThumb = getPara("goodsThumb");
		int numb = getParaToInt("numb", 1);
		String specTitle = getPara("specTitle");//规格名称
		String marketPrice = getPara("marketPrice");//选择规格的门市价
		System.out.println("specTitle============"+specTitle);
		Goods good = goodservice.findById(Integer.valueOf(goodsid));
		Record goodSeller=goodservice.getGoodsSellerById(Integer.valueOf(goodsid));
		System.out.println("------------------------------------------------"+good.toString()+"-----------------------------------"+good.getInt("ftype"));
		Record	good1 =  goodservice.getGoodsSpecType(Integer.valueOf(goodsid));
		if(StrKit.isBlank(specTitle)){			
			if (good1.getInt("stockNum") < numb) {
				renderResult(3, "库存不足");
				return;
			}
		}/*else{
			if (good.getInt("stock") < numb) {
				renderResult(3, "库存不足");
				return;
			}
		}*/
		if (StrKit.isBlank(tel)) {
			renderResult(3, "参数TEL不能为空");
			return;
		} else if (StrKit.isBlank(amount)) {
			renderResult(3, "金额不能为空");
			return;
		} else if (!StrKit.isBlank(describe) && describe.length() >= 200) {
			renderFailed("参数describe内容过长");
			return;
		}
		try {
			//ftype产品分类：713：产前，714：产后，产后不赠送商品积分
			int sppoint = 0;
			int jkpoint = 0;
			int jypoint = 0;
			String sellerId = goodSeller.get("sellerId");//商家端分配的id
			//ok商家（SE233814893）十月商家（SE201028362）所属店铺 产后商品不赠送积分，异业购买所有商品都不赠送积分，
			if("SE233814893".equals(sellerId)||"SE201028362".equals(sellerId)){
				if(good.getInt("ftype")!=714){
					sppoint = (int) SysConfig.getSppoint();
					jkpoint = (int) SysConfig.getJkpoint();
					jypoint = (int) SysConfig.getJypoint();
				}
			}
			
			int sppoints = (int) (sppoint * Double.parseDouble(amount));
			int jkpoints = (int) (jkpoint * Double.parseDouble(amount));
			int jypoints = (int) (jypoint * Double.parseDouble(amount));
			// 生成普通商品类订单的订单编号，以大写字母G开头
			String orderNum = "BE" + DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS") + CommonKit.randomNum(2);
			// 保存订单
			boolean order = new Order().set("orderNum", orderNum).set("userid", getCurrentWxUserid())
					.set("amount", amount).set("payState", OrderCode.OrderPayState.NO_PAY).set("orderState", 0)
					.set("tel", tel).set("countnum", numb).set("storeid", storeid)
					.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					.set("expireDate",
							DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"),
									"yyyy-MM-dd HH:mm:ss"))
					.set("describe", describe).set("goodsid", goodsid).set("pointType", pointType)
					.set("payPoint", point).set("goodsName", goodsName).set("thumb", goodsThumb)
					.set("sppoint", sppoints).set("jkpoint", jkpoints).set("jypoint", jypoints)
					.set("specTitle", specTitle).set("marketPrice",marketPrice).save();
			if (order) {
				if (good1.getInt("stockNum") == numb) {
					good1.set("stockNum", good1.getInt("stockNum") - numb);
					good.set("pstate", 2).update();
				} else {
					good1.set("stockNum", good1.getInt("stockNum") - numb);
					good.update();
				}
				
				/*if(spec==1){

					if (good1.getInt("stockNum") == numb) {
						good1.set("stockNum", good1.getInt("stockNum") - numb);
						good.set("pstate", 2).update();
					} else {
						good1.set("stockNum", good1.getInt("stockNum") - numb);
						good.update();
					}
				}else{
					if (good.getInt("stock") == numb) {
						good.set("stock", good.getInt("stock") - numb).set("pstate", 2).update();
					} else {
						good.set("stock", good.getInt("stock") - numb).update();
					}
				}*/

				renderSuccess(MapKit.one().put("orderNum", orderNum).getAttrs());
				return;
			} else {
				renderFailed("保存订单失败");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 立即购买
	 */
	public void saveOrder() {

		WxUser users = getCurrentWxUser();
		if (users == null) {			
			//跳转注册页
			redirect("/regist");

		} else {
			int userid = users.getInt("userid");
			if (userid != 0) {
				int goodsid = getParaToInt("goods", 0);
				String storeid = getPara("storeid");
				//获取选择商品的支付方式与规格数量
				int payType = getParaToInt("payType", 0);//支付类型
				int specType = getParaToInt("specType", 0);//规格ID
				int payNum = getParaToInt("payNum", 0);//多规格选择的商品数量
				double marketPrice=Double.parseDouble(getPara("marketPrice"));
		        
				System.out.println("payType:"+payType+"specType:"+specType+"payNum:"+payNum);				
				if (goodsid == 0 || StrKit.isBlank(storeid)) {
					redirect("/index");
					return;
				}
				Record store = goodservice.getStoreById(storeid);
				if (StrKit.notNull(store)) {
					setAttr("title", store.get("title"));
					String sellerId = store.get("sellerId");
					List<Record> list = goodservice.goodsOtherStore(storeid, sellerId, goodsid);
					setAttr("storeList", list);
				}
				if(payNum != 0){
					setAttr("payType",payType);
					setAttr("specs",goodservice.getGoodsSpecId(specType));	
					setAttr("payNum", payNum);
					setAttr("marketPrice", marketPrice);
				}
				// 查询商品详情信息
				Goods goods;
				if (getCurrentWxUser() != null) {
					// 如果当前有用户登录，则查询商品详情的同时，查询该用户与该商品的收藏关系
					goods = goodservice.findById(getCurrentWxUserid(), goodsid);
					Record goodSeller = goodservice.getGoodsSellerById(goodsid);
					User user = userservice.findByUserid(getCurrentWxUserid());
					try {
						//产品分类：713：产前，714：产后
						String sellerId = goodSeller.get("sellerId");//商家端分配的id
						//ok商家（SE233814893）十月商家（SE201028362）所属店铺 产后商品不赠送积分，异业购买所有商品都不赠送积分，
						int sppoint = 0;
						int jkpoint = 0;
						int jypoint = 0;
						if("SE233814893".equals(sellerId)||"SE201028362".equals(sellerId)){
							if(goods.getInt("ftype")!=714){
								sppoint = (int) SysConfig.getSppoint();
								jkpoint = (int) SysConfig.getJkpoint();
								jypoint = (int) SysConfig.getJypoint();
							}
						}
						setAttr("sppoint", sppoint);
						setAttr("jkpoint", jkpoint);
						setAttr("jypoint", jypoint);
						
					} catch (Exception e) {
						e.printStackTrace();
					}
					String active = getPara("active");
					setAttr("stores", store);
					setAttr("goods", goods);
					setAttr("user", user);
					setAttr("storeid", storeid);
					setAttr("active", active);// 判断是否从店铺列表页进入商品页到确认订单页
				} else {
					redirect("/index");
					return;
				}
				render("confirm.jsp");
			} else {
				redirect("/index");
			}
		}
	}

	/**
	 * 验证是否限购
	 */
	public void testBuy() {
		String orderNum = getPara("orderNum");
		int goodsid = service.getOrderByOrderNum(orderNum).getInt("goodsid");
		renderSuccess(goodservice.findById(getCurrentWxUserid(), goodsid));
	}

	/**
	 * 积分支付
	 */
	public void jfpay() {
		String orderNum = getPara(0);
		if (StrKit.isBlank(orderNum)) {
			redirect("/index");
			return;
		}
		// 查询对应的订单信息
		Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
		if (order == null) {
			redirect("/index");
			return;
		}
		// 验证订单是否有效
		if (DatetimeKit.compareDate(order.getDate("expireDate")) == -1) {
			// 如果失效，则跳转至订单详情页面
			redirect("/order/detail/" + orderNum);
			return;
		}
		User user = userservice.findByUserid(getCurrentWxUserid());
		// 计算订单总金额
		int pointsell = order.get("payPoint");
		int pointType = order.getInt("pointType");
		if (pointType == 1) {
			setAttr("point", user.getInt("sppoint"));
		} else if (pointType == 2) {
			setAttr("point", user.getInt("jkpoint"));
		} else if (pointType == 3) {
			setAttr("point", user.getInt("jypoint"));
		}
		setAttr("orderNum", orderNum);
		setAttr("pointsell", pointsell);
		setAttr("pointType", pointType);
		setAttr("order", order);
		render("jfpay.jsp");
	}

	/**
	 * 积分支付
	 */
	public void doJfPay() {
		String orderNum = getPara("orderNum");
		String flagStr = getPara("flag");
		// 查询对应的订单信息
		if (StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
			return;
		} else if (StrKit.isBlank(flagStr)) {
			renderFailed("参数FLAG不能为空");
			return;
		} else if (!flagStr.equals(String.valueOf(OrderCode.OrderPayState.NO_PAY))) {
			renderFailed("参数FLAG不正确");
			return;
		}
		// 查询订单详情并以此验证订单号
		Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);

		if (order == null) {
			renderFailed("订单不存在");
			return;
		}
		int paytype = Integer.valueOf(flagStr);
		if (paytype == OrderCode.OrderPayState.NO_PAY) {
			if (DatetimeKit.compareDate(order.getDate("expireDate")) == -1) {
				renderFailed("您的订单已过期");
				return;
			}
			Date guoDate;
			// 判断商品 是 实物 还是服务 获取兑换截止日期
			Goods goods = goodservice.getGoodById(order.getInt("goodsid"));
			if (goods.getInt("times") == 1) {
				guoDate = goods.getDate("endtime");
			} else {
				guoDate = goods.getDate("tuanEndtime");
			}
			// 计算订单总积分
			User user = userservice.findByUserid(getCurrentWxUserid());
			int pointsell = order.get("payPoint");
			int pointType = order.getInt("pointType");
			int point = 0;
			//积分变化前的积分
			/*int sppoi = user.getInt("sppoint");
			int jkpoi = user.getInt("jkpoint");
			int jypoi = user.getInt("jypoint");*/
			String pointTitle="";//积分类型名称
			if (pointType == 1) {
				point = user.getInt("sppoint");
				pointTitle="商品积分:";
			} else if (pointType == 2) {
				point = user.getInt("jkpoint");
				pointTitle="健康积分:";
			} else if (pointType == 3) {
				point = user.getInt("jypoint");
				pointTitle="教育积分:";
			}
			if (pointsell > point) {
				renderFailed("积分不足");
				return;
			} else {
				if (pointType == 1) {
					user.set("sppoint", user.getInt("sppoint") - pointsell);
				} else if (pointType == 2) {
					user.set("jkpoint", user.getInt("jkpoint") - pointsell);
				} else if (pointType == 3) {
					user.set("jypoint", user.getInt("jypoint") - pointsell);
				}
				if (user.update()) {
					String duihuanma = getCurrentWxUserid() + CommonKit.randomNum();
					order.set("payState", 2).set("orderState", 1)
							.set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
							.set("duihuanma", duihuanma);
					if (pointType == 1) {
						order.set("guoDate", DatetimeKit.getIntervalFormatDate(
								PropKit.getInt("constants.order.intervals"), "yyyy-MM-dd HH:mm:ss"));
					} else {
						order.set("guoDate", guoDate);
					}
					order.update();
					/* 积分变更 */
					UserValueLog userValue = new UserValueLog();
					userValue.set("userid", getCurrentWxUserid()).set("type", 2).set("describe", "购买宝贝")
							.set("fromOrderNum", orderNum).set("storeid", order.get("storeid"))
							.set("goodsName", order.get("goodsName"))
							.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
					if (pointType == 1) {
						userValue.set("sppoint", pointsell);
					} else if (pointType == 2) {
						userValue.set("jkpoint", pointsell);
					} else if (pointType == 3) {
						userValue.set("jypoint", pointsell);
					}
					userValue.save();
					//查询积分变更后的积分
					/*User userAfter = userservice.findByUserid(getCurrentWxUserid());*/
					//跳转路径
					//String url="http://test.bain.net.cn/order/detail/"+orderNum;
					String url= PropKit.get("constants.url_prev")+"/order/detail/"+orderNum;
					String firstDATA="您在会员中心购买的"+order.get("goodsName")+"商品已支付成功";					
					String keyword1DATA=order.get("amount")+"元";
					String keyword2DATA=pointTitle+order.get("payPoint");
					String keyword3DATA=orderNum;					
					String remarkDATA=order.get("payDate");
	
					String inviteOpenid = getCurrentWxUser().getStr("openid");
					if(order.get("amount").equals(0.0)){
						keyword1DATA="无";
					}
					if(order.get("payPoint").equals(0)){
						keyword2DATA="无";
					}
					Map<String,Object> map2 = new HashMap<String,Object>();
					map2.put("OPENID", inviteOpenid);
					map2.put("firstDATA", firstDATA);
					map2.put("keyword1DATA", keyword1DATA);
					map2.put("keyword2DATA", keyword2DATA);
					map2.put("keyword3DATA", keyword3DATA);
					map2.put("remarkDATA", remarkDATA);
					map2.put("url", url);

					try {
						System.out.println("购买消息推送");

						OrderSuccessApi.editWX_opinion(map2);
					} catch (SaveException e) {
						System.out.println("购买消息推送失败");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					service.log(order.getStr("orderNum"), 1, "用户", "积分支付", "订单支付成功，等待系统确认");
					Order orders = service.getOrderByOrderNum(orderNum);
					String phone = order.getStr("tel");
					SMSKit.sendTplSms2(phone, orders.getTimestamp("payDate"), orderNum, orders.getStr("title"),
							orders.getStr("goodsName"), orders.getTimestamp("guoDate"), duihuanma);

					Record ordermessage = service.orderMaessage(orderNum);
					String sendNum = ordermessage.get("orderNum");
					String goodsName = ordermessage.get("goodsName");
					String name = ordermessage.get("name");
					String title = ordermessage.get("store");
					String tel = ordermessage.get("tel");
					// 平台
					int type = 1;
					Record Ftype = service.FingFtype(orderNum);
					if (StrKit.notNull(Ftype)) {
						int Ttype = Ftype.get("ftype");
						if (Ttype == 713) {
							type = 2;
						} else {
							type = 3;
						}
					}
					List<Record> record = service.getBySellerPhone(type);
					for (Record Sellerphone : record) {
						SMSKit.sendTplStore(Sellerphone.get("phone"), title, goodsName, sendNum, name, tel);
					}
					// 商家
					Record records = service.findStoreSellerId(order.get("storeid"));
					int sellerid = records.getInt("sellerid");
					List<Record> recordse = service.getBySellPhone(sellerid);
					for (Record Sellerphone : recordse) {
						SMSKit.sendTplStore(Sellerphone.get("phone"), title, goodsName, sendNum, name, tel);
					}
					// 店铺
					int storeid = records.getInt("id");
					List<Record> recordst = service.getByStorePhone(storeid);
					for (Record Sellerphone : recordst) {
						SMSKit.sendTplStore(Sellerphone.get("phone"), title, goodsName, sendNum, name, tel);
					}
					renderSuccess();
					return;
				}
			}
		}
		renderFailed("支付错误");
		return;
	}

	/**
	 * 订单保存成功，展示订单编号等信息，并准备微信支付
	 */
	public void prepay() {

		String orderNum = getPara(0);
		String jifn=getPara("jifn");
		String payType=getPara("payType");
		setAttr("payType",payType);
		if(!"0".equals(jifn)){
			setAttr("jifn",jifn);
		}
		User user = userservice.findByUserid(getCurrentWxUserid());
		if (StrKit.isBlank(orderNum) || user == null) {
			redirect("/index");
			return;
		}
		// 查询对应的订单信息
		Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
		if (order == null) {
			redirect("/index");
			return;
		}
		// 验证订单是否有效
		if (DatetimeKit.compareDate(order.getDate("expireDate")) == -1) {
			// 如果失效，则跳转至订单详情页面
			redirect("/order/detail/" + orderNum);
			return;
		}
		// 获取调用微信js接口所需要的参数
		getJSApiParams(PropKit.get("constants.url_prev") + "/order/prepay/" + orderNum);

		// 计算订单总金额
		double amount = order.get("amount");
		int pointType = order.getInt("pointType");
		setAttr("pointType", pointType);
		setAttr("orderNum", orderNum);
		setAttr("amount", amount);
		setAttr("uamount", user.getDouble("money"));
		setAttr("order", order);
		render("prepay.jsp");
		return;
	}

	/**
	 * 微信预支付，生成预支付相应的参数
	 * 
	 * @param orderNum
	 *            订单号
	 * @param flag
	 *            用户所选择的支付方式，1:微信支付
	 */	
	public void doPrePay() {
		WxUser wxUser = getCurrentWxUser();
		// 判断当前登录用户是否已授权
		if (wxUser == null) {
			renderResult(1);
			return;
		}
		String orderNum = getPara("orderNum");
		String flagStr = getPara("flag");
		// 查询对应的订单信息
		if (StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
			return;
		} else if (StrKit.isBlank(flagStr)) {
			renderFailed("参数FLAG不能为空");
			return;
		} else if (!flagStr.equals(String.valueOf(OrderCode.OrderPayState.NO_PAY))) {
			renderFailed("参数FLAG不正确");
			return;
		}
		// 查询订单详情并以此验证订单号
		Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
		if (order == null) {
			renderFailed("订单不存在");
			return;
		}
		int paytype = Integer.valueOf(flagStr);
		if (paytype == OrderCode.OrderPayMethod.WEIXIN) {
			// 1：微信支付
			// 验证订单是否有效
			String startDate = DatetimeKit.getFormatDate(order.getDate("startDate"), "yyyyMMddHHmmss");
			String expireDate = DatetimeKit.getFormatDate(order.getDate("expireDate"), "yyyyMMddHHmmss");
			if (DatetimeKit.compareDate(order.getDate("expireDate")) == -1) {
				renderFailed("您的订单已过期");
				return;
			}
	
			
             
			// 计算订单总金额
			double amount = order.get("amount");
			// 获取订单总金额，并转换为以“分”为单位
			String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount, 100)).intValue()).toString();
			// openId，采用 网页授权获取 access_token API：SnsAccessTokenApi获取
			String openId = wxUser.getStr("openid");
			// 统一下单文档地址：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
			Map<String, String> params = new HashMap<String, String>();
			params.put("appid", PropKit.get("wx.pay.appId"));
			params.put("mch_id", PropKit.get("wx.pay.mch_id"));
			params.put("body", "OK妈咪微信商城");
			params.put("out_trade_no", orderNum);
			params.put("total_fee", amountStr);// 总金额单位为分
			params.put("time_start", startDate);
			params.put("time_expire", expireDate);
			String ip = CommonKit.getClientIp(getRequest());
			if (StrKit.isBlank(ip)) {
				ip = "127.0.0.1";
			}
			params.put("spbill_create_ip", ip);
			params.put("trade_type", TradeType.JSAPI.name());
			params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
			params.put("notify_url", PropKit.get("wx.pay.notifyUrl"));
			params.put("openid", openId);
			// 生成签名
			params.put("sign", PaymentKit.createSign(params, PropKit.get("wx.pay.key")));
			logger.error(params.toString());
			// 统一下单
			String xmlResult = PaymentApi.pushOrder(params);
			// 保存接口请求和响应内容日志
			new OrderPayAPIRecord().set("orderNum", orderNum).set("sendContent", params.toString())
					.set("returnContent", xmlResult).set("payMethod", paytype).set("flag", 1).save();
			// 根据响应结果给页面响应
			Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
			String return_code = result.get("return_code");
			String return_msg = result.get("return_msg");
			if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
				renderResult(3, return_msg);
				return;
			}
			String result_code = result.get("result_code");
			String result_msg = result.get("err_code_des");
			if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
				renderResult(4, result_msg);
				return;
			}
			// 以下字段在return_code 和result_code都为SUCCESS的时候有返回
			String prepay_id = result.get("prepay_id");
			// 更新订单支付方式为微信
			// order.set("paytype", OrderCode.OrderPayMethod.WEIXIN).update();
			order.set("paytype", 0).update();
	
			// 将结果响应给页面以进行下一步操作
			Map<String, String> packageParams = new HashMap<String, String>();
			packageParams.put("appId", PropKit.get("wx.pay.appId"));
			packageParams.put("timeStamp", System.currentTimeMillis() / 1000 + "");
			packageParams.put("nonceStr", System.currentTimeMillis() + "");
			packageParams.put("package", "prepay_id=" + prepay_id);
			packageParams.put("signType", "MD5");
			packageParams.put("paySign", PaymentKit.createSign(packageParams, PropKit.get("wx.pay.key")));
				
			// 将页面调用微信所需要的参数返回给页面
			renderSuccess(packageParams);
			return;
		}
		renderFailed("支付错误");
		return;
	}

	/**
	 * 余额支付
	 */
	public void ddPrePay() {
		String orderNum = getPara("orderNum");
		String flagStr = getPara("flag");
		int pointType = getParaToInt("pointType",0);
		double sppoint=0;//现金支付赠送的商品积分的比例
		double jkpoint=0;
		double jypoint=0;
		// 查询对应的订单信息
		if (StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
			return;
		} else if (StrKit.isBlank(flagStr)) {
			renderFailed("参数FLAG不能为空");
			return;
		} else if (!flagStr.equals(String.valueOf(OrderCode.OrderPayState.NO_PAY))) {
			renderFailed("参数FLAG不正确");
			return;
		}
		// 查询订单详情并以此验证订单号
		Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
		if (order == null) {
			renderFailed("订单不存在");
			return;
		}
		int payMethod = Integer.valueOf(flagStr);
		if (payMethod == OrderCode.OrderPayState.NO_PAY) {
			// 验证订单是否有效
			if (DatetimeKit.compareDate(order.getDate("expireDate")) == -1) {
				renderFailed("您的订单已过期");
				return;
			}
			Date guoDate;
			// 判断商品 是 实物 还是服务 获取兑换截止日期
			Goods goods = goodservice.getGoodById(order.getInt("goodsid"));
			Record goodSeller = goodservice.getGoodsSellerById(order.getInt("goodsid"));
			String sellerId = goodSeller.get("sellerId");//商家端分配的id
			//ok商家（SE233814893）十月商家（SE201028362）所属店铺 产后商品现金购买不赠送积分，异业购买所有商品都不赠送积分，
			if("SE233814893".equals(sellerId)||"SE201028362".equals(sellerId)){
				//产品分类：713：产前，714：产后
				if(goods.getInt("ftype")!=714){
					try {
						sppoint = (int) SysConfig.getSppoint();
						jkpoint = (int) SysConfig.getJkpoint();
						jypoint = (int) SysConfig.getJypoint();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
			if (goods.getInt("times") == 1) {
				guoDate = goods.getDate("endtime");
			} else {
				guoDate = goods.getDate("tuanEndtime");
				System.out.println("guoDateguoDate" + guoDate);
			}
			
			// 计算订单总金额
			double amount = order.get("amount");
			// 计算订单总积分
			User user = userservice.findByUserid(getCurrentWxUserid());
			int pointsell = order.get("payPoint");
			double money = user.getDouble("money");
			int point = 0;
			if (pointType == 1) {
				point = user.getInt("sppoint");
			} else if (pointType == 2) {
				point = user.getInt("jkpoint");
			} else if (pointType == 3) {
				point = user.getInt("jypoint");
			}
			if (amount > money) {
				renderFailed("余额不足");
				return;
			} else if (pointsell > point) {
				renderFailed("积分不足");
				return;
			} else {
				try {
					//判断支付的积分类型
					if (pointType == 0) {//纯现金支付
						user.set("sppoint", 
								user.getInt("sppoint") + (int) DoubleKit.mul(amount, sppoint));
						user.set("jkpoint",
								user.getInt("jkpoint") + (int) DoubleKit.mul(amount, jkpoint));
						user.set("jypoint",
								user.getInt("jypoint") + (int) DoubleKit.mul(amount, jypoint));
					}else if (pointType == 1) {	//商品积分支付
						user.set("sppoint", user.getInt("sppoint") - pointsell
								+ (int) DoubleKit.mul(amount, sppoint));
						user.set("jkpoint",
								user.getInt("jkpoint") + (int) DoubleKit.mul(amount, jkpoint));
						user.set("jypoint",
								user.getInt("jypoint") + (int) DoubleKit.mul(amount, jypoint));
					} else if (pointType == 2) {//健康积分支付
						user.set("jkpoint", user.getInt("jkpoint") - pointsell
								+ (int) DoubleKit.mul(amount, jkpoint));
						user.set("sppoint",
								user.getInt("sppoint") + (int) DoubleKit.mul(amount, sppoint));
						user.set("jypoint",
								user.getInt("jypoint") + (int) DoubleKit.mul(amount, jypoint));						
					} else if (pointType == 3) {//教育积分支付
						user.set("jypoint", user.getInt("jypoint") - pointsell
								+ (int) DoubleKit.mul(amount, jypoint));
						user.set("sppoint",
								user.getInt("sppoint") + (int) DoubleKit.mul(amount, sppoint));
						user.set("jkpoint",
								user.getInt("jkpoint") + (int) DoubleKit.mul(amount, jkpoint));
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				user.set("money", money - amount);
				if (user.update()) {
					String duihuanma = getCurrentWxUserid() + CommonKit.randomNum();
					order.set("payState", 2).set("orderState", 1)
							.set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
							.set("duihuanma", duihuanma);
					/* .set("guoDate", guoDate); */

					if (pointType == 1) {
						order.set("guoDate", DatetimeKit.getIntervalFormatDate(
								PropKit.getInt("constants.order.intervals"), "yyyy-MM-dd HH:mm:ss"));

					} else {
						order.set("guoDate", guoDate);

					}
					
					// 服务类商品的兑换时间为后台设置的时间
					Order goodsType = service.getGoodsType(orderNum);
					String types = "" + goodsType.getInt("type");
					String goodtype = "" + goodsType.getInt("goodtype");
					System.out.println("goodtype========" + goodtype);
					if (goodtype.equals("2") && (types.equals("1") || types.equals("3"))) {
						order.set("guoDate", guoDate);
					}
					order.update();
					/* 货币变更 */
					WxUser WXuser = getCurrentWxUser();
					double nowMoney = userservice.findMoney(WXuser.getInt("id"));
					System.out.println("nowMoney的值是====" + nowMoney);
					UserMoney userMoney = new UserMoney();
					userMoney.set("userid", getCurrentWxUserid()).set("amount", amount).set("type", 2)
							.set("describe", "来自订单：" + orderNum + "的消费").set("fromOrderNum", orderNum)
							.set("storeid", order.get("storeid")).set("nowAmount", nowMoney).set("orderType", 1)
							.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
					/* 积分变更 */
					UserValueLog userValue = new UserValueLog();
					UserValueLog userValues = new UserValueLog();
					if (pointsell > 0) {
						userValue.set("userid", getCurrentWxUserid()).set("type", 2).set("describe", "购买宝贝")
								.set("fromOrderNum", orderNum).set("storeid", order.get("storeid"))
								.set("goodsName", order.get("goodsName"))
								.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
						if (pointType == 1) {
							userValue.set("sppoint", pointsell);
						} else if (pointType == 2) {
							userValue.set("jkpoint", pointsell);
						} else if (pointType == 3) {
							userValue.set("jypoint", pointsell);
						}
						userValue.save();
						service.log(order.getStr("orderNum"), 1, "用户", "余额支付", "订单支付成功，等待系统确认");
					}
					// 计算订单总积分
					/*String pointTitle="";//积分类型名
					if (pointType == 1 && pointsell!=0) {
						pointTitle="商品积分:";
					} else if (pointType == 2 && poin称tsell!=0) {
						pointTitle="健康积分:";
					} else if (pointType == 3 && pointsell!=0) {
						pointTitle="教育积分:";
					}else{
						pointTitle="";
					}

					//积分变化发送消息
					//跳转路径
					
					String url= PropKit.get("constants.url_prev")+"/order/detail/"+orderNum;
					String firstDATA="您在会员中心购买的"+order.get("goodsName")+"商品已支付成功";					
					String keyword1DATA=order.get("amount")+"元";
					String keyword2DATA=pointTitle+order.get("payPoint");
					String keyword3DATA=orderNum;					
					String remarkDATA=order.get("payDate");
	
					String inviteOpenid = getCurrentWxUser().getStr("openid");
					
					if(order.get("amount").equals(0.0)){
						keyword1DATA="无";
					}
					if(order.get("payPoint").equals(0)){
						keyword2DATA="无";
					}
					Map<String,Object> map2 = new HashMap<String,Object>();
					map2.put("OPENID", inviteOpenid);
					map2.put("firstDATA", firstDATA);
					map2.put("keyword1DATA", keyword1DATA);
					map2.put("keyword2DATA", keyword2DATA);
					map2.put("keyword3DATA", keyword3DATA);
					map2.put("remarkDATA", remarkDATA);
					map2.put("url", url);

					try {
						System.out.println("购买消息推送");

						OrderSuccessApi.editWX_opinion(map2);
					} catch (SaveException e) {
						System.out.println("购买消息推送失败");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}*/

					//添加用户积分变换日志
					userValues.set("userid", getCurrentWxUserid()).set("type", 1).set("describe", "购买宝贝赠送")
							.set("fromOrderNum", orderNum).set("storeid", order.get("storeid"))
							.set("goodsName", order.get("goodsName"))
							.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
							.set("sppoint", (int) DoubleKit.mul(amount, sppoint))
							.set("jkpoint", (int) DoubleKit.mul(amount, jkpoint))
							.set("jypoint", (int) DoubleKit.mul(amount, jypoint)).save();
					
					Order orders = service.getOrderByOrderNum(orderNum);
					String phone = order.getStr("tel");
					SMSKit.sendTplSms2(phone, orders.getTimestamp("payDate"), orderNum, orders.getStr("title"),
							orders.getStr("goodsName"), orders.getTimestamp("guoDate"), duihuanma);
					Record ordermessage = service.orderMaessage(orderNum);
					String sendNum = ordermessage.get("orderNum");
					String goodsName = ordermessage.get("goodsName");
					String name = ordermessage.get("name");
					String title = ordermessage.get("store");
					String tel = ordermessage.get("tel");
					// 平台
					int type = 1;
					Record Ftype = service.FingFtype(orderNum);
					if (StrKit.notNull(Ftype)) {
						int Ttype = Ftype.get("ftype");
						if (Ttype == 713) {
							type = 2;
						} else {
							type = 3;
						}
					}
					List<Record> record = service.getBySellerPhone(type);
					for (Record Sellerphone : record) {
						SMSKit.sendTplStore(Sellerphone.get("phone"), title, goodsName, sendNum, name, tel);
					}
					// 商家
					Record records = service.findStoreSellerId(order.get("storeid"));
					int sellerid = records.getInt("sellerid");
					List<Record> recordse = service.getBySellPhone(sellerid);
					for (Record Sellerphone : recordse) {
						SMSKit.sendTplStore(Sellerphone.get("phone"), title, goodsName, sendNum, name, tel);
					}
					// 店铺
					int storeid = records.getInt("id");
					List<Record> recordst = service.getByStorePhone(storeid);
					for (Record Sellerphone : recordst) {
						SMSKit.sendTplStore(Sellerphone.get("phone"), title, goodsName, sendNum, name, tel);
					}
					renderSuccess();
					return;
				}
			}
			renderSuccess();
			return;
		}
		renderFailed("支付错误");
		return;
	}
	/**
	 * 微信支付成功改变订单状态
	 */
	public void doPrePaySuccess(){
		String orderNum = getPara("orderNum");
		if (StrKit.isBlank(orderNum)) {
			redirect("/index");
			return;
		} else {
			Order order = service.getOrderByOrder(orderNum);
			String duihuanma = getCurrentWxUserid() + CommonKit.randomNum();
			order.set("payState", 2).set("orderState", 1)
					.set("payDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					.set("duihuanma", duihuanma);	
			
			Date guoDate;
			// 判断商品 是 实物 还是服务 获取兑换截止日期
			Goods goods = goodservice.getGoodById(order.getInt("goodsid"));
			Record goodSeller = goodservice.getGoodsSellerById(order.getInt("goodsid"));
			String sellerId = goodSeller.get("sellerId");//商家端分配的id
			if (goods.getInt("times") == 1) {
				guoDate = goods.getDate("endtime");
			} else {
				guoDate = goods.getDate("tuanEndtime");
			}
			//如果是商品积分
			if (order.get("pointType").equals(1)) {
				order.set("guoDate", DatetimeKit.getIntervalFormatDate(
						PropKit.getInt("constants.order.intervals"), "yyyy-MM-dd HH:mm:ss"));
			} else {
				order.set("guoDate", guoDate);
			}
			
			// 服务类商品的兑换时间为后台设置的时间
			String types = "" + order.getInt("type");
			String goodtype = "" + order.getInt("goodtype");
			if (goodtype.equals("2") && (types.equals("1") || types.equals("3"))) {
				order.set("guoDate", guoDate);
			}

			// 计算订单总积分
			User user = userservice.findByUserid(getCurrentWxUserid());
			// 计算订单总金额
			double amounts = order.get("amount");
			//纯现金支付时增加积分
			if(order.get("payPoint").equals(0)){
				try {
					//ok商家（SE233814893）十月商家（SE201028362）所属店铺 产后商品现金购买不赠送积分，异业购买所有商品都不赠送积分，
					double sppoint=0;
					double jkpoint=0;
					double jypoint=0;
					if("SE233814893".equals(sellerId)||"SE201028362".equals(sellerId)){
						//产品分类：713：产前，714：产后
						if(goods.getInt("ftype")!=714){
							sppoint = SysConfig.getSppoint();
							jkpoint = SysConfig.getJkpoint();
							jypoint = SysConfig.getJypoint();
						}
					}
					//修改用户积分
					user.set("sppoint", 
							user.getInt("sppoint") + (int) DoubleKit.mul(amounts, sppoint));
					
					user.set("jkpoint",
							user.getInt("jkpoint") + (int) DoubleKit.mul(amounts, jkpoint));
					user.set("jypoint",
							user.getInt("jypoint") + (int) DoubleKit.mul(amounts, jypoint));
					user.update();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}			
			order.update();			
			renderSuccess();
			return;
		}		
	}
	/**
	 * 微信支付成功推送模板消息	
	 * @param orderNum
	 */
	public void doPrePaymsg(String orderNum ){
			WxUser wxUser = getCurrentWxUser();
			// 判断当前登录用户是否已授权
			if (wxUser == null) {
				renderResult(1);
				return;
			}
			// 查询订单详情并以此验证订单号
			Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
			if (order == null) {
				renderFailed("订单不存在");
				return;
			}
			
			// 支付成功消息推送
			int pointsell = order.get("payPoint");
			int pointType = order.getInt("pointType");
			String pointTitle="";//积分类型名称
			if (pointType == 1 && pointsell!=0) {
				pointTitle="商品积分:";
			} else if (pointType == 2 && pointsell!=0) {
				pointTitle="健康积分:";
			} else if (pointType == 3 && pointsell!=0) {
				pointTitle="教育积分:";
			}else{
				pointTitle="";
			}

			//跳转路径
			String url="http://test.bain.net.cn/order/detail/"+orderNum;

			String firstDATA="您在会员中心购买的"+order.get("goodsName")+"商品已支付成功";					
			String keyword1DATA=order.get("amount")+"元";
			String keyword2DATA=pointTitle+order.get("payPoint");
			String keyword3DATA=orderNum;					
			System.out.println("支付时间================"+order.getTimestamp("payDate"));
			
	       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	       String remarkDATA= sdf.format(order.getTimestamp("payDate").getTime());
			String inviteOpenid = getCurrentWxUser().getStr("openid");
			if(order.get("amount").equals(0.0)){
				keyword1DATA="无";
			}
			if(order.get("payPoint").equals(0)){
				keyword2DATA="无";
			}
			
			
			Map<String,Object> map2 = new HashMap<String,Object>();
			map2.put("OPENID", inviteOpenid);
			map2.put("firstDATA", firstDATA);
			map2.put("keyword1DATA", keyword1DATA);
			map2.put("keyword2DATA", keyword2DATA);
			map2.put("keyword3DATA", keyword3DATA);
			map2.put("remarkDATA", remarkDATA);
			map2.put("url", url);

			try {
				System.out.println("购买消息推送");

				OrderSuccessApi.editWX_opinion(map2);
			} catch (SaveException e) {
				System.out.println("购买消息推送失败");
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			

	}

	/**
	 * 交易完成
	 */
	public void tradeComplete() {
		String orderNum = getPara("orderNum");
		if (StrKit.isBlank(orderNum)) {
			redirect("/index");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
			if (order != null && order.getInt("orderState") == OrderCode.OrderState.had_CON) {
				setAttr("orderNum", orderNum);
				render("complete.jsp");
				return;
			} else {
				redirect("/index");
				return;
			}
		}
	}

	/**
	 * 订单列表
	 * 
	 * @param state
	 *            订单类型，1：全部，2：待付款，3：未使用，4：已兑换，5：已过期
	 */
	public void list() {
		int state = getParaToInt("state", 1);
		setAttr("state", state);		 
		if(getSessionAttr("userid")=="0"){			
			 redirect("/regist");
			 return;
		 }
			 render("list.jsp");	
	}

	/**
	 * 查询订单列表
	 * 
	 * @param state
	 *            订单状态，1：全部，2：待付款，3：待兑换，4：已兑换，5：已过期
	 * @param pageNum
	 *            页码
	 * @param pageSize
	 *            数量
	 */
	public void page() {

		int pageNum = getParaToInt("pageNum", 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		int state = getParaToInt("state", 1);
		Page<Order> page = service.findByPage(getCurrentWxUserid(), state, pageNum, pageSize);
		renderSuccess(page);
		return;
	}

	/**
	 * 退款列表
	 */
	public void refund() {
		render("refund.jsp");
	}

	/**
	 * 查询退款订单列表
	 */
	public void pageRefund() {
		int pageNum = getParaToInt("pageNum", 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		Page<Order> page = service.findRefundByPage(getCurrentCity(), getCurrentWxUserid(), pageNum, pageSize);
		List<Order> orderRefundList = page.getList();
		// 查询订单的商品列表供页面展示
		service.getOrderGoodsList(orderRefundList);
		renderSuccess(page);
		return;
	}
	
	/**
	 * 跳转订单详情页面
	 * 
	 * @param orderNum
	 *            订单号
	 */
	public void detail() {
		
			setAttr("orderNum", getPara(0));       
			render("detail.jsp");

	
	}

	/**
	 * 预约时间 跳转订单详情页面
	 * 
	 * @param orderNum
	 *            订单号
	 */
	public void detailComplete() {
		String bespokeDate = getPara("bespokeDate");
		String orderNum = getPara("orderNum");					
		if(!StrKit.isBlank(bespokeDate)){
			Order order = service.getOrderByOrder(orderNum);
			// 订单预约时间
			order.set("bespokeDate", bespokeDate);
			order.update();
		}
		doPrePaymsg(orderNum);//发送模板消息
		setAttr("orderNum", orderNum);

		render("detail.jsp");
	}
	
	/**
	 * 查询订单详情，及订单商品列表<br/>
	 * 注意，查询订单时，只查询订单状态“正常”、“已完成”、“已取消”的
	 * 
	 * @param orderNum
	 *            订单号
	 * @throws ParseException
	 */
	public void getDetail() throws ParseException {		
		String orderNum = getPara("orderNum");
		if (StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
			/* 消息通知 */
			UserMess userMess = new UserMess();
			if (order != null) {
				Order goodsType = service.getGoodsType(orderNum);
				String goodtype = "";// 用于接受商品类型
				String type = "";// 用于接受商品付款类型
				long Sremain = 0;// 服务类专用字段
				// 判断如果当前订单支付方式为在线支付，且未支付时，从下单时间计算出目前还有多久过期
				if (order.getInt("payState") == OrderCode.OrderPayState.NO_PAY) {
					long startTimestamp = order.getTimestamp("startDate").getTime();
					long nowTimestamp = System.currentTimeMillis();
					// 判断从下单到当前的时间，再加上5秒（此为客户端请求服务端的接口延迟时间），如果小于订单过期时间，则将该数字回传给客户端
					if (nowTimestamp - startTimestamp + 5 * 1000 < PropKit.getLong("constants.order.interval")) {
						// 计算出离过期还剩余的毫秒数返回给客户端
						order.put("remain",
								PropKit.getLong("constants.order.interval") - (nowTimestamp - startTimestamp));
					} else {
						// 相反，则认为订单已过期，修改订单状态返回给客户端
						order.set("delState", OrderCode.DelState.YES);
						if (order.update()) {
							int id = order.getInt("goodsid");
							int num = order.getInt("countnum");
							GoodSpec goodSpec = goodservice.findGoodSpecByGoodsId(id);
							//Goods good = goodservice.findById(id);
							
							if (StrKit.notNull(goodSpec)) {
								goodSpec.set("stockNum", goodSpec.getInt("stockNum") + num).update();
							}
							userMess.set("userid", order.get("userid")).set("title", "订单已过期").set("from", orderNum)
									.set("des", "您好，您的订单号为:" + order.get("orderNum") + "的订单，未在有效期支付OK妈咪已为您自动取消。")
									.set("state", 1).set("type", 1)
									.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
							renderFailed("此订单不存在");
							return;
						}
					}
				} else if (order.getInt("payState") == OrderCode.OrderPayState.HAD_PAY
						&& order.getInt("orderState") == OrderCode.OrderState.NO_CON) {
					long startTimestamps = order.getTimestamp("payDate").getTime();
					long nowTimestamps = System.currentTimeMillis();
					long endTimestamps = order.getTimestamp("guoDate").getTime();
					if (order.getInt("pointType") == 1) {
						type = "" + goodsType.getInt("type");
						goodtype = "" + goodsType.getInt("goodtype");
						if (goodtype.equals("2") && (type.equals("1") || type.equals("3"))) {
							// 从数据库获取服务类商品兑换时间
							long endTimer = order.getTimestamp("guoDate").getTime();
							long nowTimer = Calendar.getInstance().getTimeInMillis();
							/*System.out.println("结束时间" + endTimer);
							System.out.println("现在时间" + nowTimer);*/
							order.put("remain", endTimer - nowTimer);
							/*System.out.println(endTimer - nowTimer + "毫秒!!!!!!!!!!");*/
							// 判断从下单到当前的时间，再加上5秒（此为客户端请求服务端的接口延迟时间），如果小于订单过期时间，则将该数字回传给客户端
							if (nowTimestamps - startTimestamps + 5 * 1000 < PropKit
									.getLong("constants.order.intervals")) {
								// 计算出离退款期限还剩余的毫秒数返回给客户端
								Sremain = PropKit.getLong("constants.order.intervals")
										- (nowTimestamps - startTimestamps);
							}
						} else if (nowTimestamps - startTimestamps + 5 * 1000 < PropKit
								.getLong("constants.order.intervals")) {
							// 计算出离过期还剩余的毫秒数返回给客户端
							order.put("remain",
									PropKit.getLong("constants.order.intervals") - (nowTimestamps - startTimestamps));
						} else {
							// 相反，则认为订单已过期，修改订单状态返回给客户端
							if (order.set("orderState", OrderCode.OrderState.EXPIRE).update()) {
								int id = order.getInt("goodsid");
								int num = order.getInt("countnum");
//								Goods good = goodservice.findById(id);
//								good.set("stock", good.getInt("stockNum") + num).update();
								GoodSpec goodSpec = goodservice.findGoodSpecByGoodsId(id);
								if (StrKit.notNull(goodSpec)) {
									goodSpec.set("stockNum", goodSpec.getInt("stockNum") + num).update();
								}
								userMess.set("userid", order.get("userid")).set("from", order.get("orderNum"))
										.set("title", "订单已过期")
										.set("des",
												"您好，您的订单号为:" + order.get("orderNum") + "的订单，未在有效期到店内兑换，OK妈咪已为您自动处理。")
										.set("state", 1).set("type", 1)
										.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
							}
						}
					} else {

						if (nowTimestamps < endTimestamps) {
							type = "" + goodsType.getInt("type");
							goodtype = "" + goodsType.getInt("goodtype");
							if (goodtype.equals("2") && (type.equals("1") || type.equals("3"))) {
								// 从数据库获取服务类商品兑换时间
								long endTimer = order.getTimestamp("guoDate").getTime();
								long nowTimer = Calendar.getInstance().getTimeInMillis();
								/*System.out.println("结束时间" + endTimer);
								System.out.println("现在时间" + nowTimer);*/
								order.put("remain", endTimer - nowTimer);
								/*System.out.println(endTimer - nowTimer + "毫秒!!!!!!!!!!");*/
								// 判断从下单到当前的时间，再加上5秒（此为客户端请求服务端的接口延迟时间），如果小于订单过期时间，则将该数字回传给客户端
								if (nowTimestamps - startTimestamps + 5 * 1000 < PropKit
										.getLong("constants.order.intervals")) {
									// 计算出离退款期限还剩余的毫秒数返回给客户端
									Sremain = PropKit.getLong("constants.order.intervals")
											- (nowTimestamps - startTimestamps);
								}
							} else {
								goodtype = "1";
								order.put("remain", (endTimestamps - nowTimestamps));
							}
						} else {
							if (order.set("orderState", OrderCode.OrderState.EXPIRE).update()) {
								int id = order.getInt("goodsid");
								int num = order.getInt("countnum");
//								Goods good = goodservice.findById(id);
//								good.set("stock", good.getInt("stock") + num).update();
								GoodSpec goodSpec = goodservice.findGoodSpecByGoodsId(id);
								
								if (StrKit.notNull(goodSpec)) {
									goodSpec.set("stockNum", goodSpec.getInt("stockNum") + num).update();
								}
								userMess.set("userid", order.get("userid")).set("from", order.get("orderNum"))
										.set("title", "订单已过期")
										.set("des",
												"您好，您的订单号为:" + order.get("orderNum") + "的订单，未在有效期到店内兑换，OK妈咪已为您自动处理。")
										.set("state", 1).set("type", 1)
										.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
							}
						}
					}
				}

				renderSuccess(MapKit.one().put("goodtype", goodtype).put("Sremain", "" + Sremain).put("order", order)
						.getAttrs());
				return;
			} else {
				renderFailed("此订单不存在");
				return;
			}
		}
	}

	/**
	 * 跳转订单跟踪页面
	 * 
	 * @param orderNum
	 *            订单号
	 */
	public void track() {
		setAttr("orderNum", getPara(0));
		render("track.jsp");
	}

	/**
	 * 查询订单操作日志列表<br/>
	 * 
	 * @param ORDERNUM
	 *            订单号
	 */
	public void getTrack() {
		String orderNum = getPara("orderNum");
		if (StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
			if (order != null) {
				order.put("logList", service.getLogListByOrderNum(orderNum));
				// 查询订单的操作日志列表
				renderSuccess(order);
				return;
			} else {
				renderFailed("此订单不存在");
				return;
			}
		}
	}

	/**
	 * 去评价
	 */
	public void eval() {
		String orderNum = getPara(0);
		if (StrKit.isBlank(orderNum)) {
			redirect("/index");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
			if (order != null) {
				setAttr("order", order);
				render("evaluate.jsp");
				return;
			} else {
				redirect("/index");
				return;
			}
		}
	}

	/**
	 * 对订单进行评价
	 * 
	 * @param ORDERNUM
	 *            订单号
	 * @param EVAL1
	 *            商品满意度
	 * @param EVAL2
	 *            配送速度满意度
	 * @param EVAL3
	 *            服务质量满意度
	 * @param CONTENT
	 *            评价内容
	 */
	public void doEval() {
		String orderNum = getPara("orderNum");
		int eval1 = getParaToInt("eval1", 1);
		int eval2 = getParaToInt("eval2", 1);
		String content = getPara("content");
		if (StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
			return;
		} else if (StrKit.isBlank(content)) {
			renderFailed("您还未对本次购物进行评价！");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
			if (order != null) {
				if (order.getInt("evalState") == 0) {
					if (service.doEval(orderNum, getCurrentWxUserid(), eval1, eval2, content)) {
						// 更新订单评价状态为1：已评价
						order.set("evalState", 1).update();
						renderSuccess(order);
						return;
					}
					renderFailed("评价失败");
					return;
				} else {
					renderFailed("您已对本次购物评价过了！");
					return;
				}
			} else {
				renderFailed("此订单不存在");
				return;
			}
		}
	}

	/**
	 * 取消订单
	 */
	public void cancle() {
		String orderNum = getPara("orderNum");
		if (StrKit.isBlank(orderNum)) {
			redirect("/index");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
			if (order != null) {
				// 1.判断订单状态是否为“取消”、“过期”、“完成”状态
				int payState = order.getInt("payState");
				if (payState != OrderCode.OrderPayState.NO_PAY) {
					renderFailed("此订单当前不允许取消");
					return;
				}
				order.set("delState", OrderCode.DelState.YES);
				if (order.update()) {
					renderSuccess();
					return;
				} else {
					renderFailed("取消订单失败");
					return;
				}
			} else {
				renderFailed("订单不存在！");
				return;
			}
		}
	}

	/**
	 * 申请退款
	 */
	
	public void doRefund() {
		String orderNum = getPara("orderNum");
		if (StrKit.isBlank(orderNum)) {
			redirect("/index");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
			if (order != null) {
				// 1.判断订单状态是否为“取消”、“过期”、“完成”状态
				int payState = order.getInt("payState");
				int orderState = order.getInt("orderState");
				if (payState != OrderCode.OrderPayState.HAD_PAY || orderState == OrderCode.OrderState.had_CON) {
					renderFailed("此订单当前不允许申请退款");
					return;
				}
				order.set("tuistate", OrderCode.RefundState.REFUNDED);
				if (order.update()) {
					int userid = order.getInt("userid");
					double amount = order.getDouble("amount");
					int payPoint = order.getInt("payPoint");
					int pointType = order.getInt("pointType");
					int sppoint = order.getInt("sppoint");
					int jypoint = order.getInt("jypoint");
					int jkpoint = order.getInt("jkpoint");
					User user = userservice.findByUserid(userid);
					/* 货币变更 */
					UserMoney userMoney = new UserMoney();
					/* 积分变更 */
					UserValueLog userValue = new UserValueLog();
					UserValueLog userValue2 = new UserValueLog();
					/* 消息通知 */
					UserMess userMess = new UserMess();
					/* 退款日志 */
					OrderRefund orderRefund = new OrderRefund();
					if (amount > 0) {						
						// 微信支付(微信钱包或银行卡)
						if (order.getInt("paytype") == 0) {
							String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount, 100)).intValue())
									.toString();
							String refundNum = "TK" + DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")
									+ CommonKit.randomNum(2);
							Map<String, String> params = new HashMap<String, String>();
							params.put("appid", PropKit.get("wx.pay.appId"));
							params.put("mch_id", PropKit.get("wx.pay.mch_id"));
							params.put("out_trade_no", orderNum);
							params.put("out_refund_no", refundNum);
							params.put("total_fee", amountStr);// 总金额单位为分
							params.put("refund_fee", amountStr);// 退款金额单位为分
							params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
							params.put("sign", PaymentKit.createSign(params, PropKit.get("wx.pay.key")));
							logger.error(params.toString());
							// 申请退款
							Map<String, String> result = new HashMap<String, String>();
							String paternerKey = PropKit.get("wx.pay.key");
							String certPath = PathKit.getRootClassPath() + "/" + PropKit.get("wx.cert");
							System.out.println("==============微信退款======="+PaymentApi.refund(params, paternerKey, certPath));
							result = PaymentApi.refund(params, paternerKey, certPath);
							// 保存接口请求和响应内容日志
							new OrderRefundAPIRecord().set("refundNum", refundNum).set("orderNum", orderNum)
									.set("payMethod", 1).set("flag", 1).set("sendContent", params.toString())
									.set("returnContent", PaymentKit.toXml(result)).save();
							orderRefund.set("refundNum", refundNum).set("type", 2).set("orderNum", orderNum)
									.set("amount", amount).set("state", 4).save();
							/*
							 * String return_code = result.get("return_code");
							 * String return_msg = result.get("return_msg");
							 * logger.info("=============="+result+
							 * "==============="); if
							 * (StrKit.isBlank(return_code) ||
							 * !"SUCCESS".equals(return_code)) {
							 * renderResult(3,return_msg); return; } String
							 * result_code = result.get("result_code"); String
							 * result_msg = result.get("err_code_des"); if
							 * (StrKit.isBlank(result_code) ||
							 * !"SUCCESS".equals(result_code)) {
							 * renderResult(4,result_msg); return; }
							 */
							userValue2.set("userid", userid).set("type", 2).set("describe", "订单退款赠送")
									.set("storeid", order.get("storeid")).set("goodsName", order.get("goodsName"))
									.set("fromOrderNum", orderNum)
									.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
							if (payPoint > 0) {
								userValue.set("userid", userid).set("type", 1).set("describe", "订单退款")
										.set("storeid", order.get("storeid")).set("goodsName", order.get("goodsName"))
										.set("fromOrderNum", orderNum)
										.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
								if (pointType == 1) {
									user.set("sppoint", user.getInt("sppoint") + payPoint - sppoint);
									user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
									user.set("jypoint", user.getInt("jypoint") - jypoint);
									userValue.set("sppoint", payPoint).save();
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								} else if (pointType == 2) {
									user.set("jkpoint", user.getInt("jkpoint") + payPoint - jkpoint);
									user.set("sppoint", user.getInt("sppoint") - sppoint);
									user.set("jypoint", user.getInt("jypoint") - jypoint);
									userValue.set("jkpoint", payPoint).save();
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								} else if (pointType == 3) {
									user.set("jypoint", user.getInt("jypoint") + payPoint - jypoint);
									user.set("sppoint", user.getInt("sppoint") - sppoint);
									user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
									userValue.set("jypoint", payPoint).save();
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								}
							} else {
								user.set("sppoint", user.getInt("sppoint") - sppoint);
								user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
								user.set("jypoint", user.getInt("jypoint") - jypoint);
								userValue2.set("sppoint", sppoint);
								userValue2.set("jkpoint", jkpoint);
								userValue2.set("jypoint", jypoint).save();
							}
							user.update();
							// 商城钱包支付
						} else {
							user.set("money", user.getDouble("money") + amount);
							userValue2.set("userid", userid).set("type", 2).set("describe", "订单退款赠送")
									.set("storeid", order.get("storeid")).set("goodsName", order.get("goodsName"))
									.set("fromOrderNum", orderNum)
									.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
							if (payPoint > 0) {
								userValue.set("userid", userid).set("type", 1).set("describe", "订单退款")
										.set("storeid", order.get("storeid")).set("goodsName", order.get("goodsName"))
										.set("fromOrderNum", orderNum)
										.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
								if (pointType == 1) {
									user.set("sppoint", user.getInt("sppoint") + payPoint - sppoint);
									user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
									user.set("jypoint", user.getInt("jypoint") - jypoint);
									userValue.set("sppoint", payPoint).save();
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								} else if (pointType == 2) {
									user.set("jkpoint", user.getInt("jkpoint") + payPoint - jkpoint);
									user.set("sppoint", user.getInt("sppoint") - sppoint);
									user.set("jypoint", user.getInt("jypoint") - jypoint);
									userValue.set("jkpoint", payPoint).save();
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								} else if (pointType == 3) {
									user.set("jypoint", user.getInt("jypoint") + payPoint - jypoint);
									user.set("sppoint", user.getInt("sppoint") - sppoint);
									user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
									userValue.set("jypoint", payPoint).save();
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								}
							} else {
								user.set("jypoint", user.getInt("jypoint") - jypoint);
								user.set("sppoint", user.getInt("sppoint") - sppoint);
								user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
								userValue2.set("sppoint", sppoint);
								userValue2.set("jkpoint", jkpoint);
								userValue2.set("jypoint", jypoint).save();
							}
							user.update();
							WxUser WXuser = getCurrentWxUser();
							double nowMoney = userservice.findMoney(WXuser.getInt("id"));
							System.out.println("nowMoney的值是====" + nowMoney);
							userMoney.set("userid", userid).set("amount", amount).set("type", 1)
									.set("describe", "来自订单：" + orderNum + "的退款已放入您的钱包余额").set("fromOrderNum", orderNum)
									.set("orderType", 1).set("storeid", order.get("storeid")).set("nowAmount", nowMoney)
									.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
						}
						// 纯积分支付
					} else {
						userValue.set("userid", userid).set("type", 1).set("describe", "订单退款")
								.set("storeid", order.get("storeid")).set("goodsName", order.get("goodsName"));
						if (payPoint > 0) {
							if (pointType == 1) {
								user.set("sppoint", user.getInt("sppoint") + payPoint);
								userValue.set("sppoint", payPoint).save();
							} else if (pointType == 2) {
								user.set("jkpoint", user.getInt("jkpoint") + payPoint);
								userValue.set("jkpoint", payPoint).save();
							} else if (pointType == 3) {
								user.set("jypoint", user.getInt("jypoint") + payPoint);
								userValue.set("jypoint", payPoint).save();
							}
						}
						user.update();
					}
					
					// 退款消息推送					
					int pointsell = order.get("payPoint");
					int pointTypes = order.getInt("pointType");					
					String pointTitle="";//积分类型名称
					if (pointTypes == 1 && pointsell!=0) {
						pointTitle="商品积分:";
					} else if (pointTypes == 2 && pointsell!=0) {
						pointTitle="健康积分:";
					} else if (pointTypes == 3 && pointsell!=0) {
						pointTitle="教育积分:";
					}else{
						pointTitle="";
					}
					//跳转路径
					
					String url= PropKit.get("constants.url_prev")+"/order/detail/"+orderNum;
					String firstDATA="您在会员中心购买的"+order.get("goodsName")+"商品已退款成功";					
					String reasonDATA="主动申请退款";

					String  refundDATA="";

					if(!order.get("amount").equals(0.0)&&!order.get("payPoint").equals(0) ){
						refundDATA="现金:"+order.get("amount")+"元,"+pointTitle+order.get("payPoint");
					}else if(order.get("amount").equals(0.0)){
						refundDATA=pointTitle+order.get("payPoint");
					}else{
						refundDATA="现金:"+order.get("amount")+"元";
					}
					String remarkDATA="如有疑问请联系门店";
	
					String inviteOpenid = getCurrentWxUser().getStr("openid");

					Map<String,Object> map2 = new HashMap<String,Object>();
					map2.put("OPENID", inviteOpenid);
					map2.put("firstDATA", firstDATA);
					map2.put("reasonDATA", reasonDATA);
					map2.put("refundDATA", refundDATA);
					map2.put("remarkDATA", remarkDATA);
					map2.put("url", url);

					try {
						System.out.println("退款消息推送");

						OrderRefundApi.editWX_opinion(map2);
					} catch (SaveException e) {
						System.out.println("购买消息推送失败");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
					userMess.set("userid", userid).set("title", "退款成功").set("from", orderNum)
							.set("des", "订单：" + orderNum + "积分及货币已退还到您的账户").set("state", 1).set("type", 1)
							.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
					renderSuccess();
					return;
				} else {
					renderFailed("申请退款失败");
					return;
				}
			} else {
				renderFailed("订单不存在！");
				return;
			}
		}
	}

	/**
	 * 删除订单
	 */
	public void delete() {
		String orderNum = getPara("orderNum");
		if (StrKit.isBlank(orderNum)) {
			redirect("/index");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
			if (order != null) {
				// 1.判断订单状态是否为“取消”、“过期”、“完成”状态
				int payState = order.getInt("payState");
				int orderState = order.getInt("orderState");
				int tuistate = order.getInt("tuistate");
				/*
				 * if (payState == OrderCode.OrderPayState.HAD_PAY && orderState
				 * != OrderCode.OrderState.had_CON && tuistate !=
				 * OrderCode.RefundState.REFUNDED) { renderFailed("此订单当前不允许删除");
				 * return; }
				 */
				order.set("delState", OrderCode.DelState.YES);
				if (order.update()) {
					renderSuccess();
					return;
				} else {
					renderFailed("删除订单失败");
					return;
				}
			} else {
				renderFailed("订单不存在！");
				return;
			}
		}
	}

	/**
	 * 自动退款
	 */
	public void zRefund(String orderNum) {
		Order order = service.getOrderByOrderNum(getCurrentWxUserid(), orderNum);
		// 服务类商品的兑换时间为后台设置的时间
		Order goodsType = service.getGoodsType(orderNum);
		String goodtype = "" + goodsType.getInt("goodtype");
		String paytype = "" + goodsType.getInt("paytype");
		String type = "" + goodsType.getInt("type");
		// 不是包含现金服务类的商品才能自动退款
		if (order != null && (goodtype.equals("1") || (goodtype.equals("2") && (type.equals("2"))))) {
			order.set("tuistate", OrderCode.RefundState.REFUNDED);
		System.out.println("11111111");
			if (order.update()) {
				int userid = order.getInt("userid");
				double amount = order.getDouble("amount");
				int payPoint = order.getInt("payPoint");
				int pointType = order.getInt("pointType");
				int sppoint = order.getInt("sppoint");
				int jypoint = order.getInt("jypoint");
				int jkpoint = order.getInt("jkpoint");
				User user = userservice.findByUserid(userid);
				// 货币变更 
				UserMoney userMoney = new UserMoney();
				// 积分变更 
				UserValueLog userValue = new UserValueLog();
				UserValueLog userValue2 = new UserValueLog();
				 //消息通知 
				UserMess userMess = new UserMess();
				System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"+ amount+"_____________________________");
				if (amount > 0) {
					user.set("money", user.getDouble("money") + amount);
					userValue2.set("userid", userid).set("type", 2).set("describe", "订单退款")
							.set("storeid", order.get("storeid")).set("goodsName", order.get("goodsName"))
							.set("fromOrderNum", orderNum)
							.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
					if (payPoint > 0) {
						userValue.set("userid", userid).set("type", 1).set("describe", "订单退款")
								.set("storeid", order.get("storeid")).set("goodsName", order.get("goodsName"))
								.set("fromOrderNum", orderNum)
								.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
						if (pointType == 1) {
							user.set("sppoint", user.getInt("sppoint") + payPoint - sppoint);
							user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
							user.set("jypoint", user.getInt("jypoint") - jypoint);
							userValue.set("sppoint", payPoint).save();
							userValue2.set("sppoint", sppoint);
							userValue2.set("jkpoint", jkpoint);
							userValue2.set("jypoint", jypoint).save();
						} else if (pointType == 2) {
							user.set("jkpoint", user.getInt("jkpoint") + payPoint - jkpoint);
							user.set("sppoint", user.getInt("sppoint") - sppoint);
							user.set("jypoint", user.getInt("jypoint") - jypoint);
							userValue.set("jkpoint", payPoint).save();
							userValue2.set("sppoint", sppoint);
							userValue2.set("jkpoint", jkpoint);
							userValue2.set("jypoint", jypoint).save();
						} else if (pointType == 3) {
							user.set("jypoint", user.getInt("jypoint") + payPoint - jypoint);
							user.set("sppoint", user.getInt("sppoint") - sppoint);
							user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
							userValue.set("jypoint", payPoint).save();
							userValue2.set("sppoint", sppoint);
							userValue2.set("jkpoint", jkpoint);
							userValue2.set("jypoint", jypoint).save();
						}
					} else {
						if (pointType == 1) {
							user.set("sppoint", user.getInt("sppoint") - sppoint);
							user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
							user.set("jypoint", user.getInt("jypoint") - jypoint);
							userValue2.set("sppoint", sppoint);
							userValue2.set("jkpoint", jkpoint);
							userValue2.set("jypoint", jypoint).save();
						} else if (pointType == 2) {
							user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
							user.set("sppoint", user.getInt("sppoint") - sppoint);
							user.set("jypoint", user.getInt("jypoint") - jypoint);
							userValue2.set("sppoint", sppoint);
							userValue2.set("jkpoint", jkpoint);
							userValue2.set("jypoint", jypoint).save();
						} else if (pointType == 3) {
							user.set("jypoint", user.getInt("jypoint") - jypoint);
							user.set("sppoint", user.getInt("sppoint") - sppoint);
							user.set("jkpoint", user.getInt("jkpoint") - jkpoint);
							userValue2.set("sppoint", sppoint);
							userValue2.set("jkpoint", jkpoint);
							userValue2.set("jypoint", jypoint).save();
						}
					}
					user.update();
					WxUser WXuser = getCurrentWxUser();
					double nowMoney = userservice.findMoney(WXuser.getInt("id"));
					System.out.println("nowMoney的值是====" + nowMoney);
					userMoney.set("userid", userid).set("amount", amount).set("type", 1)
							.set("describe", "来自订单：" + orderNum + "的退款已放入您的钱包余额").set("fromOrderNum", orderNum)
							.set("orderType", 1).set("storeid", order.get("storeid")).set("nowAmount", nowMoney)
							.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
				} else {
					userValue.set("userid", userid).set("type", 1).set("describe", "订单退款")
							.set("storeid", order.get("storeid")).set("goodsName", order.get("goodsName"));
					if (payPoint > 0) {
						if (pointType == 1) {
							user.set("sppoint", user.getInt("sppoint") + payPoint);
							userValue.set("sppoint", payPoint).save();
						} else if (pointType == 2) {
							user.set("jkpoint", user.getInt("jkpoint") + payPoint);
							userValue.set("jkpoint", payPoint).save();
						} else if (pointType == 3) {
							user.set("jypoint", user.getInt("jypoint") + payPoint);
							userValue.set("jypoint", payPoint).save();
						}
					}
					user.update();
				}
				// 计算订单总积分
				int pointsell = order.get("payPoint");
				int pointTypes = order.getInt("pointType");				
				//积分变化前的积分				
				String pointTitle="";//积分类型名称
				if (pointTypes == 1 && pointsell!=0) {
					pointTitle="商品积分+";
				} else if (pointTypes == 2 && pointsell!=0) {				
					pointTitle="健康积分+";
				} else if (pointTypes == 3 && pointsell!=0) {				
					pointTitle="教育积分+";
				}else{				
					pointTitle="";
				}

				//积分变化发送消息
				//跳转路径
				
				String url= PropKit.get("constants.url_prev")+"/order/detail/"+orderNum;
				String firstDATA="您在会员中心购买的"+order.get("goodsName")+"商品已退款成功";					
				String reasonDATA="订单已过兑换有效期 ";

				String  refundDATA="";
				
				if(!order.get("amount").equals(0.0)&&!order.get("payPoint").equals("0") ){
					refundDATA="现金"+order.get("amount")+pointTitle+order.get("payPoint");
				}else if(order.get("amount").equals(0.0)){
					refundDATA=pointTitle+order.get("payPoint");
				}else{
					refundDATA="现金"+order.get("amount");
				}
				
				String remarkDATA="如有疑问请联系客服";

				String inviteOpenid = getCurrentWxUser().getStr("openid");

				Map<String,Object> map2 = new HashMap<String,Object>();
				map2.put("OPENID", inviteOpenid);
				map2.put("firstDATA", firstDATA);
				map2.put("reasonDATA", reasonDATA);
				map2.put("refundDATA", refundDATA);
				map2.put("remarkDATA", remarkDATA);
				map2.put("url", url);

				try {
					System.out.println("退款消息推送");

					OrderRefundApi.editWX_opinion(map2);
				} catch (SaveException e) {
					System.out.println("购买消息推送失败");
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				userMess.set("userid", userid).set("title", "退款成功").set("from", orderNum)
						.set("des", "订单：" + orderNum + "积分及货币已退还到您的账户").set("state", 1).set("type", 1)
						.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
			}
		}
	}
}
